package com.imooc.coupon.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;


public abstract class AbstractZuulFilter extends ZuulFilter {
    //扩展了currentHashMap
    RequestContext context;//是线程安全的，数据保存在每个线程的threadLocal中
    public static final String NEXT = "next";

    @Override
    /**
     * 返回为true 的时候，才会走shouldFilter方法
     */
    public boolean shouldFilter() {
        RequestContext cxt = RequestContext.getCurrentContext();
        return (Boolean) cxt.getOrDefault(NEXT, true);
    }

    @Override
    public Object run() throws ZuulException {
        context = RequestContext.getCurrentContext();
        return cRun();
    }

    protected abstract Object cRun();

    Object fali(int code, String msg) {
        context.set(NEXT, false);
        context.setSendZuulResponse(false);//Zuul响应设置为false,不需要执行其他的过滤器了
        context.getResponse().setContentType("text/html;charset=UTF-8");
        context.setResponseStatusCode(code);
        context.setResponseBody(String.format("{\"result\":\"%s!\"}", msg));
        return null;
    }

    Object success() {
        context.set(NEXT, true);
        return null;
    }

}
